//
//  Bill_HM_VC.m
//  zhiche--delivery
//
//  Created by 王亚陆 on 16/12/7.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "Bill_HM_VC.h"
#import "Bill_HM_Cell.h"
#import "RootViewController.h"
#import "Common.h"
#import "NullDataView.h"
#import <MJRefresh.h>
#import <Masonry.h>
#import "OtherDetailVC.h"
@interface Bill_HM_VC ()<UIGestureRecognizerDelegate>
{
    UIImageView * nav;
    UITableView * table;
    Common * com;
    RootViewController * TabBar;
    NSMutableDictionary * dataSouceDic;
    
    NSMutableArray * dataSouceArr;
    int page;
    int totalPage;
    NullDataView * nullView;
}
@end

@implementation Bill_HM_VC


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.orderID = [[NSString alloc]init];
        self.monthText = [[NSString alloc]init];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = GrayColor;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    TabBar = [RootViewController defaultsTabBar];
    dataSouceArr = [[NSMutableArray alloc]init];
    com = [[Common alloc]init];
    
    page = 1;
    totalPage = 1;
    dataSouceDic = [[NSMutableDictionary alloc]init];
    nav = [self createNav:@"账单明细"];
    [self.view addSubview:nav];
    [self createTable];
    
    nullView = [[NullDataView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - 64) andTitle:@"暂无账单" andImageName:@"形状"];
    nullView.backgroundColor = GrayColor;
    
}

-(void)createTable{
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, Main_Width, Main_height-64) style:UITableViewStylePlain];
    
    table.backgroundColor = GrayColor;
    [table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    table.delegate = self;
    table.dataSource = self;
    [table.mj_header beginRefreshing];
    table.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    
    [self.view addSubview:table];
}


-(void)downRefresh{
    
    [table.mj_header endRefreshing];
    [table.mj_footer endRefreshing];
    page = 1;
    [self loadData];
    NSLog(@"刷新");
}

-(void)upRefresh{
    
    if (page!=totalPage) {
        page ++;
        [self loadData];
        [table.mj_footer endRefreshing];
        
    }else{
        table.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [table.mj_header endRefreshing];
    NSLog(@"加载%d%d",page,totalPage);
    
}

-(void)loadData{
    
    
    NSString * string = [NSString stringWithFormat:@"%@?pageNo=%d&pageSize=10&billId=%@",Find_Bill_list_Url,page,self.orderID];
    
    [com afPostRequestWithUrlString:string parms:nil finishedBlock:^(id responseObj) {
        
        NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray * arr = [NSMutableArray arrayWithArray:dicObj[@"data"][@"cTurnovers"]];
        
        if ([arr count]>0) {
            [nullView removeFromSuperview];
            if (page == 1) {
                [dataSouceArr removeAllObjects];
                dataSouceArr = arr;
            }else{
                for (int i=0; i<[arr count]; i++) {
                    
                    [dataSouceArr addObject:arr[i]];
                }
            }
            [table reloadData];

        }else{
            [table addSubview:nullView];
        }
        
        totalPage = [dicObj[@"data"][@"page"][@"totalPage"] intValue];
        
    } failedBlock:^(NSString *errorMsg) {
        
    }];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [TabBar setTabBarHidden:YES];
    
    [self loadData];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *str=@"str";
    Bill_HM_Cell  * cell =  [tableView dequeueReusableCellWithIdentifier:str];
    if (cell ==nil) {
        cell = [[Bill_HM_Cell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    

    
//    NSString * orderString = [NSString stringWithFormat:@"订单号：%@",dataSouceArr[indexPath.row][@"bussinessId"]];
//    NSLog(@"%@",orderString);
//    NSMutableAttributedString *content = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@", orderString]];
//    NSRange contentRange = {0,[content length]};
//    [content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
//    cell.orderLabel.attributedText = content;
//    
    
    
    
    NSString * string = [NSString stringWithFormat:@"订单号：%@",dataSouceArr[indexPath.row][@"bussinessId"]];
    
    NSMutableAttributedString *stringLabel = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange strRange = {3,[string length]-3};

    [stringLabel addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:strRange];  //设置颜色
    cell.orderLabel.attributedText = stringLabel;
    
    
    
    
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%.2f",[dataSouceArr[indexPath.row][@"orderActPay"] floatValue]];
    cell.addressLabel.text = [NSString stringWithFormat:@"%@-%@",dataSouceArr[indexPath.row][@"departName"],dataSouceArr[indexPath.row][@"receiptName"]];

    
//    NSString * billType = [NSString stringWithFormat:@"%@",dataSouceArr[indexPath.row][@"billType"]];
//
//    if ([billType isEqualToString:@"10"]) {
//        cell.sortLabel.text = @"同城配送";
//        
//    }else if ([billType isEqualToString:@"20"]){
//        cell.sortLabel.text = @"城际运输";
//
//    }else{
//        cell.sortLabel.text = @"人送代驾";
//
//    }
    
    
    
    NSString * billTypeText = [NSString stringWithFormat:@"%@",dataSouceArr[indexPath.row][@"billTypeText"]];

    cell.sortLabel.text = billTypeText;

    
    
    
    NSString * dateLabel = [NSString stringWithFormat:@"%@",[dataSouceArr[indexPath.row][@"createTime"] substringWithRange:NSMakeRange(0, 10)]];
    cell.dateLabel.text = dateLabel;


    
    cell.orderBtn.indexpath = indexPath;

    [cell.orderBtn addTarget:self action:@selector(pressOrderBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}


-(void)pressOrderBtn:(NewBtn*)sender{
    
    NSInteger index = sender.indexpath.row;
    NSString * string = dataSouceArr[index][@"orderId"];
    
    
    OtherDetailVC * detail = [[OtherDetailVC alloc]init];
    detail.orderId = string;
    [self.navigationController pushViewController:detail animated:YES];
//    NSLog(@"string id ======%@",string);

    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 105*kHeight;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return dataSouceArr.count;
//        return 3;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    
    return 1;
}


-(void)createUIAlertController:(NSString*)title
{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 43*kHeight;
    
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, 44*kHeight)];
    view.backgroundColor = WhiteColor;
    UILabel * label = [com createUIlabel:self.monthText andFont:FontOfSize12 andColor:littleBlackColor];
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view.mas_left).with.offset(16*kWidth);
        make.centerY.mas_equalTo(view.mas_centerY);
    }];
    
    UIView * viewline = [[UIView alloc]init];
    viewline.backgroundColor = LineGrayColor;
    [view addSubview:viewline];
    [viewline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(view.mas_right);
        make.bottom.mas_equalTo(view.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 0.5));
    }];
    
    
    return view;
}
-(NSString *)backString:(NSString *)string
{
    //    NSString * str = [NSString stringWithFormat:@"%@",string];
    if ([string isEqual:[NSNull null]]) {
        return @"";
    } else {
        return string;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
